package com.example.listviewdemo_1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;

import com.example.listviewdemo_1.bean.Data;
import com.example.listviewdemo_1.bean.VResponse;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Call.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {


    ListView  lvJoke ;
    VResponse vResponse;
    List<Data> jokeList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);  //笑话大全 ：195d3e531c813bdcf32aa1e8ecd39c3b
        lvJoke = findViewById(R.id.lv_joke);

        onlineJoke();

    }


    private void onlineJoke(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url("https://v.juhe.cn/joke/content/list.php?"+
                        "key=195d3e531c813bdcf32aa1e8ecd39c3b&page=2&pagesize=10&sort=asc&time=1418745237").get().build();
                Call call  = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();

                    Gson gson = new Gson();
                    vResponse  =gson.fromJson(response.body().string(),VResponse.class);
                    Log.e("vResponse",vResponse.getResult().getData().get(1).getContent());

                    Message message = new Message();
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
    private Handler handler = new Handler() {
        public void handleMessage (Message message){
            jokeList=  vResponse.getResult().getData();
            MyAdapter myAdapter = new MyAdapter(jokeList,MainActivity.this);
            lvJoke.setAdapter(myAdapter);

        }
    };
}
